# views.py 路由 + 视图函数
import os
from flask import request
from flask import  Blueprint
import hashlib
from .utils.api_utils import APIUtils
from .models import *
blus = Blueprint("user", __name__)

# 注册
@blus.route('/api/register', methods=['POST'])
def user_register():
    required_fields = ['username', 'password']
    is_valid, message = APIUtils.validate_json(request.json, required_fields)
    if not is_valid:
        return APIUtils.error_response(message, status_code=400)
    username = request.json['username']
    password = request.json['password']

    # 检查用户名是否已存在
    existing_user = User.query.filter_by(username=username).first()
    if existing_user:
        return APIUtils.error_response("用户名已经存在!", status_code=400)

    # 哈希处理密码
    hashed_password = hashlib.sha256(password.encode()).hexdigest()

    # 创建新用户
    new_user = User(username=username, password=hashed_password)

    db.session.add(new_user)
    db.session.commit()

    return APIUtils.success_response(message="登录成功!")

@blus.route('/api/login', methods=['POST'])
def user_login():
    required_fields = ['username', 'password']
    is_valid, message = APIUtils.validate_json(request.json, required_fields)
    if not is_valid:
        return APIUtils.error_response(message, status_code=400)
    username = request.json['username']
    password = request.json['password']
    user = User.query.filter_by(username=username).first()
    if user is None:
        return APIUtils.error_response("用户名错误或不存在！", status_code=401)
    hashed_password = hashlib.sha256(password.encode()).hexdigest()
    if hashed_password != user.password:
        return APIUtils.error_response("密码错误或不存在！", status_code=401)
    return APIUtils.success_response(data={'userId': user.id, 'username': user.username}, message="登录成功！")

@blus.route('/change_password', methods=['POST'])
def change_password():
    required_fields = ['username', 'old_password', 'new_password']
    is_valid, message = APIUtils.validate_json(request.json, required_fields)

    if not is_valid:
        return APIUtils.error_response(message, status_code=400)

    username = request.json['username']
    old_password = request.json['old_password']
    new_password = request.json['new_password']

    user = User.query.filter_by(username=username).first()

    if user is None:
        return APIUtils.error_response("用户不存在！", status_code=404)
    hashed_old_password = hashlib.sha256(old_password.encode()).hexdigest()

    if hashed_old_password != user.password:
        return APIUtils.error_response("旧密码错误！", status_code=401)

    # 哈希处理新密码
    hashed_new_password = hashlib.sha256(new_password.encode()).hexdigest()
    user.password = hashed_new_password

    db.session.commit()
    return APIUtils.success_response(message="密码修改成功！")


@blus.route('/api/user/del/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    # 根据用户 ID 查询用户
    user = User.query.get(user_id)

    if user is None:
        return APIUtils.error_response("用户不存在！", status_code=404)

    # 检查是否为 admin 用户
    if user.username.lower() == 'admin':
        return APIUtils.error_response("无法删除管理员账户！", status_code=403)

    # 删除用户
    db.session.delete(user)
    db.session.commit()

    return APIUtils.success_response(message="用户删除成功！")

# 用户管理
@blus.route('/api/users/page', methods=['GET'])
def get_users():
    # 获取分页参数，默认为第 1 页，每页 10 条记录
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    # 获取 username 参数，如果没有则为 None
    username = request.args.get('username', type=str)

    # 构建查询，先查询所有用户
    query = User.query

    # 如果提供了 username，则根据 username 进行筛选
    if username:
        query = query.filter(User.username.like(f'%{username}%'))

    # 执行分页查询
    users_pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    # 获取用户数据
    users = users_pagination.items

    # 将用户数据转为 JSON 格式
    users_list = []
    for user in users:
        users_list.append({
            'id': user.id,
            'username': user.username,
            'password': user.password,
            # 其他需要返回的字段
        })

    # 构建响应数据，包括分页信息
    response = {
        'list': users_list,
        'page': {
            'total': users_pagination.total,  # 总记录数
            'page': users_pagination.page,  # 当前页码
            'limit': users_pagination.per_page  # 每页记录数
        }
    }

    return APIUtils.success_response(data=response, message="获取用户列表成功")



# 论文创建
@blus.route('/api/item', methods=['POST'])
def create_item():
    data = request.get_json()

    # 检查name和user_id是否已经存在
    existing_item = db.session.query(Item).filter_by(name=data['name'], user_id=data['userId']).first()
    if existing_item:
        return APIUtils.error_response(message="该论文标题已存在，请使用不同的标题！")

    new_item = Item(
        name=data['name'],
        path=data['path'],
        is_view=data['isView'],
        user_id=data['userId'],
    )
    db.session.add(new_item)
    db.session.commit()
    return APIUtils.success_response(message="创建成功!")

# 论文更新
@blus.route('/api/item/<int:id>', methods=['PUT'])
def update_item(id):
    data = request.get_json()
    item = Item.query.get(id)

    if not item:
        return APIUtils.error_response(message="没找到对象论文信息!")
    item.name = data['name']
    item.path = data['path']
    item.isView = data['isView']
    item.view = data['view']
    item.user_id = data['user_id']
    item.create_time = data['create_time']

    db.session.commit()

    return APIUtils.success_response(message="更新成功!")

#论文删除
@blus.route('/api/item/<int:id>', methods=['DELETE'])
def delete_item(id):
    item = Item.query.get(id)

    if not item:
        return APIUtils.error_response(message="没找到对象论文信息!")
    db.session.delete(item)
    db.session.commit()
    return APIUtils.success_response(message="删除成功!")


# 论文管理
@blus.route('/api/items/page', methods=['GET'])
def get_items():
    # 获取分页参数，默认为第 1 页，每页 10 条记录
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    # 获取 name 参数，如果没有则为 None
    name = request.args.get('name', type=str)

    # 构建查询，先查询所有论文
    query = Item.query
    # 如果提供了 name，则根据 name 进行筛选
    if name:
        query = query.filter(Item.name.like(f'%{name}%'))

    # 执行分页查询
    items_pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    # 获取论文数据
    items = items_pagination.items

    # 将论文数据转为 JSON 格式
    items_list = []
    for item in items:
        items_list.append({
            'id': item.id,
            'name': item.name,
            'path': item.path,
            'is_view': item.is_view,
            'view': item.view,
            'userId': item.user_id,
            'createTime': item.create_time,
            # 其他需要返回的字段
        })

    # 构建响应数据，包括分页信息
    response = {
        'list': items_list,
        'page': {
            'total': items_pagination.total,  # 总记录数
            'page': items_pagination.page,  # 当前页码
            'limit': items_pagination.per_page  # 每页记录数
        }
    }

    return APIUtils.success_response(data=response, message="获取论文列表成功")
